package com.cygsunri.wisdompark.callback.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cygsunri.common.CommonConstant;
import com.cygsunri.exception.BusinessException;
import com.cygsunri.response.ResultCodeEnum;
import com.cygsunri.wisdompark.bussiniss.vo.BaseDataResult;
import com.cygsunri.wisdompark.callback.entity.TbMthcarPeople;
import com.cygsunri.wisdompark.callback.service.NoticeService;
import com.cygsunri.wisdompark.callback.service.TbMthcarPeopleService;
import com.cygsunri.wisdompark.callback.vo.notice.*;
import com.cygsunri.wisdompark.util.CommonUtil;
import com.cygsunri.wisdompark.util.HttpUtils;
import com.cygsunri.wisdompark.util.MD5Util;
import com.cygsunri.wisdompark.util.id.SnowFlakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *
 * </p>
 *
 * @author cygsunri
 * @since 2021/8/10
 */
@Slf4j
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private TbMthcarPeopleService tbMthcarPeopleService;

    @Override
    public BaseDataResult addMthCarPerson(MthCarPeopleDTO mthCarPeopleDTO) {
        //http://openapi.szymzh.com/Api/Inform/AddPerson
        log.info("NoticeServiceImpl addMthCarPerson ====>> "+JSON.toJSONString(mthCarPeopleDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            mthCarPeopleDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(mthCarPeopleDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            mthCarPeopleDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/AddPerson", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(mthCarPeopleDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
                if(!"0".equals(result.getCode())){
                    TbMthcarPeople mthcarPeople = new TbMthcarPeople();
                    BeanUtils.copyProperties(mthCarPeopleDTO,mthcarPeople);
                    mthcarPeople.setId(SnowFlakeIdWorker.generateNextIdStr());
                    JSONObject jsonObject = (JSONObject) JSON.toJSON(result.getData());
                    mthcarPeople.setUserNo(jsonObject.getString("userNo"));
                    boolean flag = tbMthcarPeopleService.save(mthcarPeople);
                    if(!flag){
                        throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"月租车用户信息保存失败,请核实!");
                    }
                }
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"新增月租车用户通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult addMthCar(MthCarDTO mthCarDTO) {
        //http://openapi.szymzh.com/Api/Inform/AddMthCar
        log.info("NoticeServiceImpl addMthCar ====>> "+JSON.toJSONString(mthCarDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            mthCarDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(mthCarDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            mthCarDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/AddMthCar", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(mthCarDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"新增月租车通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult openGate(OpenGateDTO openGateDTO) {
        //http://openapi.szymzh.com/Api/Inform/OpenGate
        log.info("NoticeServiceImpl openGate ====>> "+JSON.toJSONString(openGateDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            openGateDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(openGateDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            openGateDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/OpenGate", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(openGateDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"远程开闸通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult closeGate(CloseGateDTO closeGateDTO) {
        //http://openapi.szymzh.com/Api/Inform/CloseGate
        log.info("NoticeServiceImpl closeGate ====>> "+JSON.toJSONString(closeGateDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            closeGateDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(closeGateDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            closeGateDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/CloseGate", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(closeGateDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"远程关闸通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult addVisitorCar(AddVisitorCarDTO addVisitorCarDTO) {
        //http://openapi.szymzh.com/Api/Inform/AddVisitorCar
        log.info("NoticeServiceImpl addVisitorCar ====>> "+JSON.toJSONString(addVisitorCarDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            addVisitorCarDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(addVisitorCarDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            addVisitorCarDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/AddVisitorCar", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(addVisitorCarDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"访客车辆新增通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult deleteVisitorCar(DeleteVisitorCarDTO deleteVisitorCarDTO) {
        //http://openapi.szymzh.com/Api/Inform/DeleteVisitorCar
        log.info("NoticeServiceImpl deleteVisitorCar ====>> "+JSON.toJSONString(deleteVisitorCarDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            deleteVisitorCarDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(deleteVisitorCarDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            deleteVisitorCarDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/DeleteVisitorCar", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(deleteVisitorCarDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"访客车辆删除通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult setCarLockStatus(SetCarLockStatusDTO setCarLockStatusDTO) {
        //http://openapi.szymzh.com/Api/Inform/SetCarLockStatus
        log.info("NoticeServiceImpl setCarLockStatus ====>> "+JSON.toJSONString(setCarLockStatusDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            setCarLockStatusDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(setCarLockStatusDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            setCarLockStatusDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/SetCarLockStatus", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(setCarLockStatusDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"车辆锁定与解锁通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public BaseDataResult failMonthCar(FailMonthCarDTO failMonthCarDTO) {
        //http://openapi.szymzh.com/Api/Inform/FailMonthCar
        log.info("NoticeServiceImpl setCarLockStatus ====>> "+JSON.toJSONString(failMonthCarDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            failMonthCarDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(failMonthCarDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            failMonthCarDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/FailMonthCar", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(failMonthCarDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"注销月租车失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    @Override
    public void failMonthCars(List<FailMonthCarDTO> failMonthCars) {
        failMonthCars.forEach(failMonthCarDTO ->{
            //http://openapi.szymzh.com/Api/Inform/FailMonthCar
            log.info("NoticeServiceImpl setCarLockStatus ====>> "+JSON.toJSONString(failMonthCarDTO));
            BaseDataResult result = new BaseDataResult();
            try {
                DecimalFormat df = new DecimalFormat("#.000000000");
                Random r = new Random();
                String rand = df.format(r.nextDouble() * 5);
                failMonthCarDTO.setRand(rand);
                Map<String, Object> stringObjectMap = CommonUtil.objectToMap(failMonthCarDTO);
                Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
                String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
                String stringSignTemp=urlParamsByMap+"&"+CommonConstant.APP_SECRET;
                String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
                log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
                failMonthCarDTO.setSign(strSign);
                HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inform/FailMonthCar", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(failMonthCarDTO));
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                    result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
                }else{
                    throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"注销月租车失败,请核实!");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
            }
        });

    }
}
